<?php

//
// +------------------------------------------------------------------------+
// | PHP Version 5.4                                                        |
// +------------------------------------------------------------------------+
// | Copyright (c) All rights reserved.                                     |
// +------------------------------------------------------------------------+
// | 世纪车来车往(北京）网络科技有限公司 版权所有！                           |
// | TEL:010-63732365  HOTLINE:400-6688-365  EMAIL:clcw@clcw.com.cn         |
// | $Revision: 1.0 $                                                       |
// +------------------------------------------------------------------------+
// | Author: xiangminghu@clcw.com.cn                                        |
// +------------------------------------------------------------------------+
//

namespace AuctionCore\Other;

use AuctionCore\Account\Back\Employee;
use AuctionCore\CarResource\CarModel as CarModel;
use AuctionCore\CarResource\CarReport;
use AuctionCore\System\AuctionException;

/**
 * 定制车辆信息
 *
 * @author Xmh
 */
class Custom {

    private $CustomModel;
    private $CarModel;

    public function __construct() {
        $this->CustomModel = M("custom");
        $this->CarModel = new CarModel();
    }

    /**
     * 获得用户定制信息列表
     */
    public function get_custom_list($page, $size, $params) {
        $page = (int) $page < 1 ? 1 : (int) $page;
        $size = (int) $size < 1 ? 10 : (int) $size;
        $map = array();
        /**
         * 条件查询
         * 1、登记ID 2、手机号 3、预算 4、车型 5、渠道 6、所在地 7、操作人 8、开始时间、结束时间 
         */
        if ($params['id']) {
            $map['id'] = array('eq', $params['id']);
        }
        if ($params['status']) {
            $map['status'] = array('eq', $params['status']);
        }
        if ($params['phone']) {
            $map['phone'] = array('like', '%' . $params['phone'] . '%');
        }
        if ($params['budget']) {
            $map['budget'] = array('eq', $params['budget']);
        }
        if ($params['car_type']) {
            $map['car_type'] = array('eq', $params['car_type']);
        }
        if ($params['comefrom']) {
            $map['comefrom'] = array('eq', $params['comefrom']);
        }
        if ($params['addr']) {
            $map['addr'] = array('eq', $params['addr']);
        }
        if ($params['emp']) {
            $map['emp_id'] = array('eq', $params['emp']);
        }
        if ($params['start_time']) {
            $map['create_at'] = array('egt', $params['start_time'] . ' 00:00:00');
        }
        if ($params['end_time']) {
            $map['create_at'] = array('elt', $params['end_time'] . ' 23:59:59');
        }
        if ($params['start_time'] && $params['end_time']) {
            $map['create_at'] = array(array('egt', $params['start_time'] . ' 00:00:00'), array('elt', $params['end_time'] . ' 23:59:59'));
        }
        $cols = "*";
        $order = "id DESC";
        $total = $this->CustomModel->where($map)->count();
        $list = $this->CustomModel->alias('c')
                ->field($cols)
                ->where($map)
                ->limit($size)
                ->page($page)
                ->order($order)
                ->select();
//        echo M()->getLastSql();
        $list_info = array();
        $addr = new \AuctionCore\Other\Address();
        foreach ($list as $k => $v) {
            $list_info[$k]['id'] = $v['id'];
            $emp = Employee::user_info_id($v['emp_id']);
            $list_info[$k]['emp'] = $emp['real_name'];
            $list_info[$k]['phone'] = $v['phone'];
            $list_info[$k]['budget'] = $v['budget'];
            $list_info[$k]['addr'] = $addr->get_name_by_code($v['addr']);
            $list_info[$k]['car_type'] = $v['car_type'];
            $list_info[$k]['comefrom'] = $v['comefrom'];
            $list_info[$k]['custom_time'] = $v['custom_time'];
            $list_info[$k]['created_at'] = $v['created_at'];
        }
        $result = array(
            'list' => $list_info,
            'total' => $total
        );
        return $result;
    }

    /**
     * 提交定制信息
     */
    public function custom_add($data) {
        $data['created_at'] = date("Y-m-d H:i:s", time());
        $condition['phone'] = $data['phone'];
        $condition['status'] = array(array('neq', 3), array('neq', 4),'OR');
        $total = $this->CustomModel->where($condition)->count();
        if ($total > 0) {
            AuctionException::make_throw('200075');
        }
        $data['uid'] = M("user")->where(['pwd_mobile'=>$data['phone']])->getField('uid');
        return $this->CustomModel->add($data);
    }

    /**
     * 获取定制信息详情
     * @param int $id
     */
    public function get_custom_info($id) {
        $condition['id'] = $id;
        $list = $this->CustomModel->where($condition)->find();
        $addr = new \AuctionCore\Other\Address();
        $list['addr'] = $addr->get_name_by_code($list['addr']);
        return $list;
    }

    /**
     * 处理定制信息
     */
    public function update_custom_post($data) {
        $data['custom_time'] = date("Y-m-d H:i:s", time());
        return $this->CustomModel->save($data);
    }

    /**
     * 获得用户定制车源列表
     */
    public function custom_cars_list($page, $size, $params) {
        $page = (int) $page < 1 ? 1 : (int) $page;
        $size = (int) $size < 1 ? 20 : (int) $size;
        $map = array();
        $condition = array();
        if($params['phone']){
            $condition['phone'] = array('eq',$params['phone']);
        }
        if($params['uid']){
            $condition['uid'] = array('eq',$params['uid']);
        }
//        $custom = $this->CustomModel->field("id,mbrand_id,brand_id,series_id,budget,car_type")
//                        ->where($condition)->find();
        $custom_id = $this->CustomModel->where($condition)->getField('id');
        if (!$custom_id) {
            AuctionException::make_throw('200074');
        }
        $map['cu.id'] = array('eq',$custom_id);
        $map['cu.status']  = array('eq','3');
//        $mbrand_id = $custom['mbrand_id'];
//        $brand_id = $custom['brand_id'];
//        $series_id = $custom['series_id'];
//        $budget = $custom['budget'];
//        $car_type = $custom['car_type'];
//        if ($mbrand_id) {
//            $map['mbrand_id'] = array('eq', $mbrand_id);
//        }
//        if ($brand_id) {
//            $map['brand_id'] = array('eq', $brand_id);
//        }
//        if ($series_id) {
//            $map['series_id'] = array('eq', $series_id);
//        }
//        if ($budget) {
//            switch ($budget) {
//                case 1:
//                    $map['c.reserve_price'] = array('elt', '50000');
//                    break;
//                case 2:
//                    $map['c.reserve_price'] = array(array('gt', '50000'), array('elt', '100000'));
//                    break;
//                case 3:
//                    $map['c.reserve_price'] = array(array('gt', '100000'), array('elt', '150000'));
//                    break;
//                case 4:
//                    $map['c.reserve_price'] = array(array('gt', '150000'), array('elt', '200000'));
//                    break;
//                case 5:
//                    $map['c.reserve_price'] = array('gt', '200000');
//                    break;
//                default:
//                    break;
//            }
//        }
//        if ($car_type) {
//            switch ($car_type) {
//                case 1:
//                    $map['c.car_type'] = array('IN', '1,2,3,4,11');
//                    break;
//                case 2:
//                    $map['c.car_type'] = array('eq', '10');
//                    break;
//                case 3:
//                    $map['c.car_type'] = array('elt', '8');
//                    break;
//                case 4:
//                    $map['c.car_type'] = array('elt', '9');
//                    break;
//                case 5:
//                    $map['c.car_type'] = array('egt', '15');
//                    break;
//                default:
//                    break;
//            }
//        }
        $cols = "c.car_id,c.car_no,c.mbrand_id,c.brand_id,c.series_id,c.model_id,c.first_reg_date
                ,c.composite_state,c.accident_level,c.pointer_mileage,c.plate_prefix,c.plate_suffix,c.reserve_price";
        $total = M('Custom')->alias('cu')
                ->join(" LEFT JOIN ".C('DB_PREFIX') . "custom_intent cui ON cu.`id`=cui.`custom_id`")
                ->join(" INNER JOIN ".C('DB_PREFIX') . "cars c ON cui.`car_id`= c.`car_id`")
                ->where($map)
                ->count();
        $res = M('Custom')->alias('cu')->field($cols)
                ->join(" LEFT JOIN ".C('DB_PREFIX') . "custom_intent cui ON cu.`id`=cui.`custom_id`")
                ->join(" INNER JOIN ".C('DB_PREFIX') . "cars c ON cui.`car_id`= c.`car_id`")
                ->where($map)
                ->limit($size)
                ->page($page)
                ->select();
//        echo M()->getLastSql();
        $list = array();
        foreach ($res as $key => $value) {
            $brand = $this->CarModel->get_model_by_id($value['brand_id'], 'brand');
            $series = $this->CarModel->get_model_by_id($value['series_id'], 'series');
            $model = $this->CarModel->get_model_by_id($value['model_id']);
            $list[$key]['car_no'] = '车辆编号：' . $value['car_no'];
            $list[$key]['car_id'] = $value['car_id'];
            $car_model = M('car_model')->field('name,year')->where(array('model_id' => $value['model_id']))->find();
            if (!empty($car_model['year']) || !empty($car_model['name'])) {
                $list[$key]['car_name'] = $brand['name'] . ' ' . $series['name'] . ' ' . $model['year'] . '款' . $model['name'];
            } else {
                $list[$key]['car_name'] = $series['name'] . ' ' . $value['car_cc'] . ($value['turbo'] ? 'T' : 'L') . ' ' . C('GEARBOX.' . $value['gearbox']);
            }
            $first_reg_date = date('Y年m月', strtotime($value['first_reg_date']));
            $pointer_mileage = round($value['pointer_mileage'] / 10000, 2);
            $plate_number = C('PLATE_PREFIX.' . $value['plate_prefix']) . substr($value['plate_suffix'], 0, 1);
            $list[$key]['desc'] = $first_reg_date . '初登/' . $pointer_mileage . '万公里/' . $plate_number;
            $list[$key]['price'] = strip_tags(format_money($value['reserve_price'])) . '元';
            $list[$key]['composite_level'] = $value['composite_state'] . $value['accident_level'];
            $car = new \AuctionCore\CarResource\Car($value['car_id']);
            $cond = "car_id='" . $value['car_id'] . "' AND pic_key='p_left_front45'";
            $pics = $car->get_pics('car_pictures', $cond);
            $list[$key]['image'] = $pics[0]['pic_url'];
        }
        $result = array(
            'currentpage' => $page,
            'pagesize' => $size,
            'maxcount' => $total,
            'maxpage' => ceil($total / $size),
            'list' => $list
        );
        return $result;
    }

    /**
     * 获得定制车源详情
     */
    public function custom_cars_info($car_id) {
        $cols = "c.car_id,c.car_no,c.mbrand_id,c.brand_id,c.series_id,c.model_id,c.first_reg_date
                ,c.composite_state,c.accident_level,c.pointer_mileage,c.plate_prefix,c.plate_suffix,c.reserve_price";
        $car = M('cars')->alias('c')->field($cols)->find($car_id);
        if (!$car) {
            AuctionException::make_throw("600002");
        }
        $car_info = array();
        $car_info['car_no'] = '车辆编号：' . $car['car_no'];
        $car_info['car_id'] = $car['car_id'];
        $brand = $this->CarModel->get_model_by_id($car['brand_id'], 'brand');
        $series = $this->CarModel->get_model_by_id($car['series_id'], 'series');
        $model = $this->CarModel->get_model_by_id($car['model_id']);
        $car_model = M('car_model')->field('name,year')->where(array('model_id' => $car['model_id']))->find();
        if (!empty($car_model['year']) || !empty($car_model['name'])) {
            $car_info['car_name'] = $brand['name'] . ' ' . $series['name'] . ' ' . $model['year'] . '款' . $model['name'];
        } else {
            $car_info['car_name'] = $series['name'] . ' ' . $value['car_cc'] . ($value['turbo'] ? 'T' : 'L') . ' ' . C('GEARBOX.' . $value['gearbox']);
        }
        $first_reg_date = date('Y年m月', strtotime($car['first_reg_date']));
        $pointer_mileage = round($car['pointer_mileage'] / 10000, 2);
        $plate_number = C('PLATE_PREFIX.' . $car['plate_prefix']) . substr($car['plate_suffix'], 0, 1);
        $car_info['desc'] = $first_reg_date . '初登/' . $pointer_mileage . '万公里/' . $plate_number;
        $car_info['price'] = strip_tags(format_money($car['reserve_price'])) . '元';
        $car_info['composite_level'] = $car['composite_state'] . $car['accident_level'];
        $car_resource = new \AuctionCore\CarResource\Car($car['car_id']);
        $cond = "car_id='" . $car['car_id'] . "' AND pic_key='p_left_front45'";
        $pics = $car_resource->get_pics('car_pictures', $cond);
        $car_info['image'] = $pics[0]['pic_url'];
        //厂商指导价
        $refer_price = M('car_model')->where('model_id=' . $car['model_id'])->getField('refer_price');
        $refer_price_format = sprintf("%.2f", $refer_price);
        //购置税计算
        $purchase_price = ($refer_price * 10000) / (1 + 0.17);
        $purchase_tax = round(($purchase_price * 0.1) / 10000, 2);
        $car_info['newprice'] = ($refer_price_format + $purchase_tax) . '万元';
        $report = new CarReport($car_id);
        $base = $report->app_base_info();
        $base_info = array();
        if ($base) {
            $base['first_reg_date']['value'] = date("Y年m月d日", strtotime($base['first_reg_date']['value'])) . '初登';
            $base['ex_factory_date']['value'] = date("Y年m月d日", strtotime($base['ex_factory_date']['value']));
            $base_info = $this->getObjArr($base);
            foreach ($base_info as $kb => $vb) {
                $base_info_list[$kb] = array_slice($vb, 0, 2);
            }
        }
        $car_info['config'] = $base_info_list;
        $base_pics_info = $report->get_base_pics_app();
        $car_info['images'] = $base_pics_info;
        return $car_info;
    }

    /**
     * 获取我的订制信息
     */
    public function get_my_custom($uid){
        return M('custom')->where("uid='".$uid."'")->order("id DESC")->find();
    }

    /**
     * 获取意向车源列表
     */
    public function get_intent_list($page=1,$size=20,$map){
            //au_custom_sale_intent ,au_custom,au_custom_intent,au_car_sale,au_cars
            $cols = "car.car_no,car.series_id,car.car_cc,car.turbo,car.gearbox,
                    car.first_reg_date,car.pointer_mileage,car.emission,car.plate_prefix,car.plate_suffix,
                    cs.sale_price";

            $count = M('custom_sale_intent')->alias('csi')
                ->join(C('DB_PREFIX')."custom_intent ci ON ci.id=csi.intent_id")
                ->join(C('DB_PREFIX')."custom c  ON c.id=ci.custom_id")
                ->join(C('DB_PREFIX')."car_sale cs ON cs.sale_id=csi.sale_id")
                ->join(C('DB_PREFIX')."cars car ON car.car_id=cs.car_id")
                ->where($map)->count();

            $list = M('custom_sale_intent')->alias('csi')
                ->field($cols)
                ->join(C('DB_PREFIX')."custom_intent ci ON ci.id=csi.intent_id")
                ->join(C('DB_PREFIX')."custom c  ON c.id=ci.custom_id")
                ->join(C('DB_PREFIX')."car_sale cs ON cs.sale_id=csi.sale_id")
                ->join(C('DB_PREFIX')."cars car ON car.car_id=cs.car_id")
                ->where($map)->page($page)->limit($size)->select();

            foreach($list as $key=>$value){
                $list[$key] = $value;
                $car = new \AuctionCore\CarResource\Car($value['car_id']);
                //车辆图片
                $car_pic = $car->get_pic_by_key($value['car_id'],'p_left_front45');
                $list[$key]['car_pic'] = $car_pic['pic_url'];//TODO:加图片处理参数指定宽高
                //车型
                $cm = new \AuctionCore\CarResource\CarModel();
                $series = $cm->get_model_by_id($value['series_id'], 'series');
                //
                $list[$key]['car_model'] = $series['name'] . ' ' . $value['car_cc'] . ($value['turbo'] ? 'T' : 'L') . ' ' . C('GEARBOX.' . $value['gearbox']);
                //销售
                $list[$key]['sale_price'] = format_money($value['sale_price']);
            }
            $ret = array();
            $ret['count'] = $count;
            $ret['list'] = $list;
            return $ret;
    }

    /**
     * 转换报告信息为对象格式
     * @param type $arr
     * @return type
     */
    private function getObjArr($arr) {
        $i = 0;
        $arr_info = array();
        foreach ($arr as $va) {
            $arr_info[$i] = $va;
            $i++;
        }
        return $arr_info;
    }

}
